﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using Easy.Extend;
using Easy.Web.CMS;
using Easy.Web.CMS.Page;
using Easy.Web.CMS.Widget;
using Microsoft.Practices.ServiceLocation;
using System.Web.Mvc;
using Easy.CMS.List.Models;
using Easy.MetaData;
using System;
using Easy.Data;
using Easy.CMS.List.ViewModel;
using Easy.Web.CMS.Data;
using System.Data;
using System.Text;
using System.Net.Http;
using Easy.Web.CMS.Helper;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Easy.CMS.List.Service
{
    public class ListTops_Table_WidgetService : WidgetService<ListTops_Table_Widget>
    {
        public override WidgetPart Display(WidgetBase widget, ControllerContext controllerContext)
        {
            var currentWidget = widget as ListTops_Table_Widget;

            var viewModel = new ListTops_Table_ViewModel()
            {
                Widget = currentWidget,
                JsonResult = string.Empty,
                Columns = new List<string>(),
            };

            int itemLen = currentWidget.ItemLength != null ? Convert.ToInt32(currentWidget.ItemLength) : currentWidget.ItemLength.GetValueOrDefault();
            currentWidget.ItemLength = itemLen;

            int top = currentWidget.Tops ?? 5;
            string formCode = currentWidget.FormCode;
            string listId = currentWidget.ListId;

            if (!string.IsNullOrEmpty(listId) && !string.IsNullOrEmpty(formCode))
            {
                StringBuilder select = new StringBuilder("[Id] ");
                HttpContent content = new StringContent(JsonConvert.SerializeObject(new
                {
                    CollectionName = "ListField",
                    JsonData = string.Format("[{{\"ValueType\":\"String\",\"Name\":\"list_id\",\"Value\":\"{0}\",\"Operation\":\"EQ\"}}]", listId)
                }));
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var listDisplay = APIHelper.RunApiPost(Urls.ApiHost, "api/mp/list/findfirst/", content);
                if (!string.IsNullOrEmpty(listDisplay))
                {
                    var jsonObject = ((JObject)JsonConvert.DeserializeObject(listDisplay));
                    var displays = ((JArray)(JsonConvert.DeserializeObject(jsonObject["display_field"].ToString()))).ToList();
                    foreach (var v in displays)
                    {
                        string column = v["code"].ToString();
                        select.AppendFormat(", [{0}]", column);
                        viewModel.Columns.Add(column);
                    }

                    string sql = string.Format("select top {0} * from {1} order by [createtime] desc, [Id]", top, formCode);
                    DataSet ds = YunPanDbHelper.Query(sql);
                    if (ds.HasData())
                    {
                        viewModel.JsonResult = ds.GetJsonString();
                    }
                }
            }
            return widget.ToWidgetPart(viewModel);
        }
    }
}